import store from '../store';

function dateFormat(date = new Date(), fmt = "YYYY-mm-dd HH:MM:SS") {
	let ret;
	const opt = {
		"Y+": date.getFullYear().toString(), // 年
		"m+": (date.getMonth() + 1).toString(), // 月
		"d+": date.getDate().toString(), // 日
		"H+": date.getHours().toString(), // 时
		"M+": date.getMinutes().toString(), // 分
		"S+": date.getSeconds().toString() // 秒
		// 有其他格式化字符需求可以继续添加，必须转化成字符串
	};
	for (let k in opt) {
		ret = new RegExp("(" + k + ")").exec(fmt);
		if (ret) {
			fmt = fmt.replace(ret[1], (ret[1].length == 1) ? (opt[k]) : (opt[k].padStart(ret[1].length, "0")))
		};
	};
	return fmt;
}


function dateTransition(date, format) {
	format = format || 'yyyy-MM-dd hh:mm:ss';
	let ret;
	const o = {
		"Y+": date.getFullYear().toString(), // 年
		"M+": date.getMonth() + 1, //month
		"d+": date.getDate(), //day
		"h+": date.getHours(), //hour
		"m+": date.getMinutes(), //minute
		"s+": date.getSeconds(), //second
		"q+": Math.floor((date.getMonth() + 3) / 3), //quarter
		"S": date.getMilliseconds() //millisecond
	};
	if (/(y+)/.test(format)) format = format.replace(RegExp.$1,
		(date.getFullYear() + "").substr(4 - RegExp.$1.length));
	for (let k in o)
		if (new RegExp("(" + k + ")").test(format))
			format = format.replace(RegExp.$1,
				RegExp.$1.length === 1 ? o[k] :
				("00" + o[k]).substr(("" + o[k]).length));
	return format;
}




function timestampToTime(time) { // 时间戳为10位需*1000，时间戳为13位的话不需乘1000
	var date = new Date(time * 1000)
	let y = date.getFullYear()
	let MM = date.getMonth() + 1
	MM = MM < 10 ? ('0' + MM) : MM
	let d = date.getDate()
	d = d < 10 ? ('0' + d) : d
	let h = date.getHours()
	h = h < 10 ? ('0' + h) : h
	let m = date.getMinutes()
	m = m < 10 ? ('0' + m) : m
	let s = date.getSeconds()
	s = s < 10 ? ('0' + s) : s
	return y + '-' + MM + '-' + d + ' ' + h + ':' + m + ':' + s
}

function formatTime(time) {
	if (typeof time !== 'number' || time < 0) {
		return time
	}

	var hour = parseInt(time / 3600)
	time = time % 3600
	var minute = parseInt(time / 60)
	time = time % 60
	var second = time

	return ([hour, minute, second]).map(function(n) {
		n = n.toString()
		return n[1] ? n : '0' + n
	}).join(':')
}

function formatLocation(longitude, latitude) {
	if (typeof longitude === 'string' && typeof latitude === 'string') {
		longitude = parseFloat(longitude)
		latitude = parseFloat(latitude)
	}

	longitude = longitude.toFixed(2)
	latitude = latitude.toFixed(2)

	return {
		longitude: longitude.toString().split('.'),
		latitude: latitude.toString().split('.')
	}
}

function dictToObj({
	list = [],
	label = "label",
	value = "value",
	children = "children"
}) {
	var res = {};
	if (list && list.length > 0) {
		list.forEach(items => {
			res[value] = items[label];
			if (items[children] && items[children].length) {
				Object.assign(res, dictToObj(items[children]));
			}
		})
	}
	return res;
}

var dateUtils = {
	UNITS: {
		'年': 31557600000,
		'月': 2629800000,
		'天': 86400000,
		'小时': 3600000,
		'分钟': 60000,
		'秒': 1000
	},
	humanize: function(milliseconds) {
		var humanize = '';
		for (var key in this.UNITS) {
			if (milliseconds >= this.UNITS[key]) {
				humanize = Math.floor(milliseconds / this.UNITS[key]) + key + '前';
				break;
			}
		}
		return humanize || '刚刚';
	},
	format: function(dateStr) {
		var date = this.parse(dateStr)
		var diff = Date.now() - date.getTime();
		if (diff < this.UNITS['天']) {
			return this.humanize(diff);
		}
		var _format = function(number) {
			return (number < 10 ? ('0' + number) : number);
		};
		return date.getFullYear() + '/' + _format(date.getMonth() + 1) + '/' + _format(date.getDate()) + '-' +
			_format(date.getHours()) + ':' + _format(date.getMinutes());
	},
	parse: function(str) { //将"yyyy-mm-dd HH:MM:ss"格式的字符串，转化为一个Date对象
		var a = str.split(/[^0-9]/);
		return new Date(a[0], a[1] - 1, a[2], a[3], a[4], a[5]);
	}
};

var PI = 3.1415926535897932384626;
var a = 6378245.0;
var ee = 0.00669342162296594323;


function transformlat(lng, lat) {
	var lat = +lat;
	var lng = +lng;
	var ret = -100.0 + 2.0 * lng + 3.0 * lat + 0.2 * lat * lat + 0.1 * lng * lat + 0.2 * Math.sqrt(Math.abs(lng));
	ret += (20.0 * Math.sin(6.0 * lng * PI) + 20.0 * Math.sin(2.0 * lng * PI)) * 2.0 / 3.0;
	ret += (20.0 * Math.sin(lat * PI) + 40.0 * Math.sin(lat / 3.0 * PI)) * 2.0 / 3.0;
	ret += (160.0 * Math.sin(lat / 12.0 * PI) + 320 * Math.sin(lat * PI / 30.0)) * 2.0 / 3.0;
	return ret
};

function transformlng(lng, lat) {
	var lat = +lat;
	var lng = +lng;
	var ret = 300.0 + lng + 2.0 * lat + 0.1 * lng * lng + 0.1 * lng * lat + 0.1 * Math.sqrt(Math.abs(lng));
	ret += (20.0 * Math.sin(6.0 * lng * PI) + 20.0 * Math.sin(2.0 * lng * PI)) * 2.0 / 3.0;
	ret += (20.0 * Math.sin(lng * PI) + 40.0 * Math.sin(lng / 3.0 * PI)) * 2.0 / 3.0;
	ret += (150.0 * Math.sin(lng / 12.0 * PI) + 300.0 * Math.sin(lng / 30.0 * PI)) * 2.0 / 3.0;
	return ret
};

function out_of_china(lng, lat) {
	var lat = +lat;
	var lng = +lng;
	// 纬度3.86~53.55,经度73.66~135.05
	return !(lng > 73.66 && lng < 135.05 && lat > 3.86 && lat < 53.55);
};

// wgs84 -> 火星坐标系
function wgs84togcj02(lng, lat) {
	var lat = +lat;
	var lng = +lng;
	if (out_of_china(lng, lat)) {
		return [lng, lat]
	} else {
		var dlat = transformlat(lng - 105.0, lat - 35.0);
		var dlng = transformlng(lng - 105.0, lat - 35.0);
		var radlat = lat / 180.0 * PI;
		var magic = Math.sin(radlat);
		magic = 1 - ee * magic * magic;
		var sqrtmagic = Math.sqrt(magic);
		dlat = (dlat * 180.0) / ((a * (1 - ee)) / (magic * sqrtmagic) * PI);
		dlng = (dlng * 180.0) / (a / sqrtmagic * Math.cos(radlat) * PI);
		var mglat = lat + dlat;
		var mglng = lng + dlng;
		// return [mglng, mglat]

		return `${mglng},${mglat}`
	}
};


function wgs84togcj03(lng, lat) {
	var lat = +lat;
	var lng = +lng;
	if (out_of_china(lng, lat)) {
		return [lng, lat]
	} else {
		var dlat = transformlat(lng - 105.0, lat - 35.0);
		var dlng = transformlng(lng - 105.0, lat - 35.0);
		var radlat = lat / 180.0 * PI;
		var magic = Math.sin(radlat);
		magic = 1 - ee * magic * magic;
		var sqrtmagic = Math.sqrt(magic);
		dlat = (dlat * 180.0) / ((a * (1 - ee)) / (magic * sqrtmagic) * PI);
		dlng = (dlng * 180.0) / (a / sqrtmagic * Math.cos(radlat) * PI);
		var mglat = lat + dlat;
		var mglng = lng + dlng;
		return [mglng, mglat]
	}
};




function goBack(url, index = 2, success = undefined) {
	if (url === undefined) {
		return;
	}
	if (index == 1) {
		// 关闭当前页，返回上一页面或多级页面。
		uni.navigateBack({
			delta: url,
			animationType: 'pop-out',
			animationDuration: 300,
			success: success
		});
	} else if (index == 2) {
		// 保留当前页，跳转到非tabbar页面，使用uni.navigateBack可以返回到原页面。
		uni.navigateTo({
			url: url,
			animationType: 'pop-in',
			animationDuration: 300,
			success: success
		})
	} else if (index == 3) {
		// 跳转到 tabBar 页面，并关闭其他所有非 tabBar 页面。
		uni.switchTab({
			url: url,
			animationType: 'pop-in',
			animationDuration: 300,
			success: success
		})
	} else if (index == 4) {
		// 关闭所有页面，打开到应用内的某个页面。
		uni.reLaunch({
			url: url,
			animationType: 'pop-in',
			animationDuration: 300,
			success: success
		})
	} else if (index == 5) {
		// 关闭当前页面，跳转到应用内的某个页面。
		uni.redirectTo({
			url: url,
			success: success
		});
	}
}

/**
 * 对象深拷贝
 */
function deepClone(data) {
	var type = getObjType(data);
	var obj;
	if (type === 'array') {
		obj = [];
	} else if (type === 'object') {
		obj = {};
	} else {
		//不再具有下一层次
		return data;
	}
	if (type === 'array') {
		for (var i = 0, len = data.length; i < len; i++) {
			obj.push(deepClone(data[i]));
		}
	} else if (type === 'object') {
		for (var key in data) {
			obj[key] = deepClone(data[key]);
		}
	}
	return obj;
}


/**
 * 传入一个秒数，返回这个秒数所代表的时长
 * 例如:3天 11小时 21分钟 40秒
 */
function getStrByTime(s) {
	if (s < 1) {
		return "";
	}
	if (s < 60) {
		return s + "秒";
	}
	let m = parseInt(s / 60),
		ss = s % 60;
	if (m < 60) {
		return `${m}分钟 ${ss}秒`;
	}
	let h = parseInt(m / 60),
		mm = m % 60;
	if (h < 24) {
		return `${h}小时 ${mm}分钟 ${ss}秒`;
	}
	let d = parseInt(h / 24),
		hh = h % 24;
	return `${d}天 ${hh}小时 ${mm}分钟 ${ss}秒`;
}


export const getObjType = obj => {
	var toString = Object.prototype.toString;
	var map = {
		'[object Boolean]': 'boolean',
		'[object Number]': 'number',
		'[object String]': 'string',
		'[object Function]': 'function',
		'[object Array]': 'array',
		'[object Date]': 'date',
		'[object RegExp]': 'regExp',
		'[object Undefined]': 'undefined',
		'[object Null]': 'null',
		'[object Object]': 'object'
	};

	return map[toString.call(obj)];
};

// 把对象序列化为表单
function formDataInit(data, keyBefore = '', formData) {
	if (!data) {
		return {}
	}
	if (!formData) {
		formData = new FormData();
	}
	Object.keys(data).forEach((keys) => {
		const items = data[keys];
		switch (getObjType(items)) {
			case 'object':
				formDataInit(items, keyBefore + keys + '.', formData);
				break;
			case 'array':
				items.forEach((item, index) => {
					if (getObjType(item) == 'object') {
						formDataInit(item, keyBefore + keys + `[${index}].`, formData);
					} else {
						if (item !== undefined)
							formData.append(keyBefore + keys + `[${index}]`, item);
					}
				})
				break;
			default:
				if (items !== undefined)
					formData.append(keyBefore + keys, items);
				break;
		}
	});
	return formData;
}


function AMapGraspRoadDriving(locations) { // 时间戳为10位需*1000，时间戳为13位的话不需乘1000
	const graspRoad = new AMap.GraspRoad();
	return new Promise((resolve, reject) => {
		let prevPoints = [];
		// 过滤重复的点位
		locations = locations.filter(item => {
			if (prevPoints.lon == item.lon && prevPoints.lat == item.lat && !prevPoints.v1) {
				return false;
			}
			prevPoints = item;
			return true;
		});
		let posSec;
		const points = locations.map((item) => {
			let tm = item.posSec / 1000;
			if (posSec) {
				tm = tm - posSec;
			} else {
				posSec = tm;
			}
			return {
				x: item.lon,
				y: item.lat,
				sp: item.v1,
				ag: item.direction,
				tm,
			};
		});
		const pages = Math.ceil(points.length / 500);
		let res = [];
		let resIndex = 0;
		let resState = true;
		for (let i = 0; i < pages; i++) {
			const pointsSlice = points.slice(500 * i, 500 * (i + 1));
			graspRoad.driving(pointsSlice, (error, result) => {
				resIndex++;
				if (!error) {
					const newPath = result.data.points;
					res[i] = newPath;
				} else {
					resState = false;
				}
				if (resIndex == pages) {
					if (resState) {
						res = res.flat();
						res = res.map((item) => {
							return new AMap.LngLat(item.x, item.y);
						});
						resolve(res);
					} else {
						reject();
					}
				}
			});
		}
	});

}

// 用于单个的坐标系转换
// function getAmapConvert(LngLat, type = "gps") {
// 	return new Promise((resolve, reject) => {
// 		AMap.convertFrom(LngLat, type, function(status, result) {
// 			if (status === 'complete' && result.info === "ok") {
// 				let res = result.locations[0]
// 				resolve([res.lng, res.lat])
// 			} else {
// 				reject()
// 			}
// 		})
// 	})
// }
// 用于单个的逆地理解析
function getAddress(longitude, latitude, key = 'd2d26c9238b8b5499147c5b3186a294f') {
	return new Promise((resolve, reject) => {
		uni.request({
			header: {
				'Content-Type': 'application/text',
			},
			//注意:这里的key值需要高德地图的 web服务生成的key  只有web服务才有逆地理编码
			url: `https://restapi.amap.com/v3/geocode/regeo?output=JSON&location=${longitude},${latitude}&key=${key}`,
			success(result) {
				if (result.statusCode === 200) {
					console.log(result)
					let res = result?.data?.regeocode?.formatted_address
					// return res
					resolve(res)
				} else {
					reject()
				}
			},
			// fail(err) {
			// 	reject(err)
			// 	console.log(err, "获取位置失败信息")
			// }
		})
	})

}
function getSelectPath(value = '') {
	let localdata = store.getters.getRegionData;
	const res = {
		text: '',
		path: []
	};
	if (!value || !localdata || localdata.length == 0) {
		return res;
	}
	var path = [];
	topfor:
		for (let top of localdata) {
			if (value.startsWith(top.value)) {
				path[0] = top;
				if (top.children) {
					for (let child of top.children) {
						if (value.startsWith(child.value)) {
							path[1] = child;
							if (child.children) {
								for (let item of child.children) {
									if (item.value == value) {
										path[2] = item;
										break topfor;
									}
								}
							}
						}
					}
				}
			}
		}
	res.text = path.map((item) => {
		return item.title;
	}).join('');
	res.path = path.map((item) => {
		return item.value;
	});
	return res;
}

export {
	formatTime,
	dateFormat,
	formatLocation,
	dateUtils,
	goBack,
	dictToObj,
	wgs84togcj02,
	timestampToTime,
	wgs84togcj03,
	getStrByTime,
	formDataInit,
	deepClone,
	AMapGraspRoadDriving,
	dateTransition,
	// getAmapConvert,
	getAddress,
	getSelectPath
}
